Public Class frmProject
    Inherits System.Windows.Forms.Form
    'todo: speed up display by not forcing save of ini file when each item is set
    Private Sub frmProject_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadForm()
    End Sub

    Private Sub LoadForm()
        Try
            With lvwProjects
                .Items.Clear()
                For Each Section As String In IniFile.GetProjectNames
                    Dim lvitem As New ListViewItem(Section)
                    lvitem.SubItems.Add(IniFile.GetKey(Section, clsWRDBIniFile.enumKey.Description))
                    .Items.Add(lvitem)
                Next
                .Columns(0).Width = -1
                .Columns(1).Width = -2
                For i As Integer = 0 To .Items.Count - 1
                    If .Items(i).SubItems(0).Text = IniFile.GetKey(clsWRDBIniFile.enumSection.Application, clsWRDBIniFile.enumKey.AppLastProjectName) Then
                        .Items(i).Selected = True
                        .FocusedItem = .Items(i)
                        .EnsureVisible(i)
                    End If
                Next
                .Focus()
            End With
            Me.Text = "Open & Manage Projects" & IIf(String.Equals(AppDataPath, My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\WRDB", StringComparison.OrdinalIgnoreCase), "", " - " & AppDataPath.Replace(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "<My Documents>"))
            ToolTip1.SetToolTip(btnConfig, "Current WRDB directory: " & AppDataPath.Replace(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "<My Documents>"))
            'IniFile.SaveAndClose()
        Catch ex As IO.IOException
            WarningMsg(IniFile.ErrorText(ex))
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub lvwProjects_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwProjects.DoubleClick
        Me.btnOpen.PerformClick()
    End Sub

    Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
        'don't need to be supervisor to create new project, or could get stuck if only a single protected project
        'If Not SupervisorEnabled() Then Exit Sub
        If MainForm.FileNewProject() Then Close()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            SetProject(lvwProjects.SelectedItems(0).Text)
            With New frmPrefs
                .ShowDialog()
                .Dispose()
            End With
            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            Dim OldName As String = Me.lvwProjects.SelectedItems(0).Text
            Dim NewName As String = InputBox("Enter the new name for this project:", "Rename Project", OldName).Trim
            If NewName = "" Then Exit Sub
            If IniFile.RenameProject(OldName, NewName) Then
                SetProject(NewName)
                'Project.DB.ExecuteNonQuery("UPDATE Tracking SET Project_Name='{0}' WHERE Project_Name='{1}'", NewName, OldName)
                LoadForm()
            Else
                ErrorMsg(String.Format("Unable to rename project {0} to {1}; the new project name may already exist.", OldName, NewName))
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            Dim ProjectName As String = Me.lvwProjects.SelectedItems(0).Text
            If Project IsNot Nothing AndAlso ProjectName.ToUpper = Project.Name.ToUpper Then
                WarningMsg("You cannot delete the currently active project; please select a different project first.")
                LoadForm()
                Exit Sub
            End If
            Dim IniFile As New clsWRDBIniFile()
            With IniFile
                Dim dbTypeString As String = .GetKey(ProjectName, clsWRDBIniFile.enumKey.DatabaseType, "")
                If dbTypeString <> "" Then
                    Dim dbType As clsDB.enumDBType = System.Enum.Parse(GetType(clsDB.enumDBType), dbTypeString)
                    Dim DBFile As String = clsProject.ReplaceMyDocs(.GetKey(ProjectName, clsWRDBIniFile.enumKey.DataSource)) 'server name or filename
                    Dim DBName = .GetKey(ProjectName, clsWRDBIniFile.enumKey.DatabaseName)
                    Select Case MessageBox.Show(StringFormat("This will remove the selected project specification from the WRDB configuration file so that it will no longer show up in this project list. You will also be allowed to optionally delete any tables and/or database files that are referenced by this project.\n\nDo you want to proceed?"), "Delete Project", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                        Case Windows.Forms.DialogResult.OK
                            Select Case dbType
                                Case clsDB.enumDBType.Access, clsDB.enumDBType.Firebird_Embedded, clsDB.enumDBType.SQLite, clsDB.enumDBType.SQL_Server_CE
                                    If WarningMsgFmt("Do you want to delete the database file ({0}), thus permanently deleting all data and Support tables associated with this project?", DBFile.Replace("\", "/")) = Windows.Forms.DialogResult.OK Then
                                        If My.Computer.FileSystem.FileExists(DBFile) Then My.Computer.FileSystem.DeleteFile(DBFile)
                                    End If
                                Case clsDB.enumDBType.Firebird, clsDB.enumDBType.MySQL, clsDB.enumDBType.Oracle, clsDB.enumDBType.SQL_Server
                                    Try
                                        Dim ThisProject As clsProject = Nothing
                                        'try to connect so can delete tables; if fails, just remove project
                                        ThisProject = New clsProject(ProjectName)
                                        With ThisProject
                                            If .DB.TestConnectionQuick(CONNECTIONTIMEOUT) Then
                                                Dim lst As Generic.List(Of String) = .GetTableListAll
                                                If WarningMsgFmt("Do you want to permanently delete all {0} data and Support tables in the server database ({1}) associated with this project (the database itself must be removed by a database administrator)?", lst.Count, .DB.DataSource) = Windows.Forms.DialogResult.OK Then
                                                    For Each tbl As String In lst
                                                        .DB.DropTable(tbl)
                                                    Next
                                                End If
                                            End If
                                            .Dispose()
                                        End With
                                    Catch ex As Exception
                                    End Try
                            End Select
                            RemoveProject(ProjectName)
                        Case Windows.Forms.DialogResult.Cancel
                            Exit Sub
                    End Select
                End If
            End With

            'Select Case MessageBox.Show(StringFormat("This will remove the selected project specification from the WRDB configuration file so that it will no longer show up in this project list. You will also be allowed to optionally delete any tables and/or database files that are referenced by this project.\n\nDo you want to proceed?"), "Delete Project", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
            '    Case Windows.Forms.DialogResult.OK
            '        My.Computer.FileSystem.DeleteFile(DBFile)
            '        RemoveProject(ProjectName)
            '        'Select Case .DB.DatabaseType
            '        '    Case clsDB.enumDBType.Access, clsDB.enumDBType.Firebird_Embedded, clsDB.enumDBType.SQLite
            '        '        If WarningMsgFmt("Do you want to delete the database file ({0}), thus permanently deleting all data and Support tables associated with this project?", .DB.DataSource.Replace("\", "/")) = Windows.Forms.DialogResult.OK Then
            '        '            Dim DBFile As String = .DB.DataSource
            '        '            .DB.Connection.Close()
            '        '            .DB.Connection.Dispose()
            '        '            .DB.Dispose()
            '        '            .Dispose()
            '        '            ThisProject = Nothing
            '        '            My.Computer.FileSystem.DeleteFile(DBFile)
            '        '        End If
            '        '    Case clsDB.enumDBType.Firebird, clsDB.enumDBType.MySQL, clsDB.enumDBType.Oracle, clsDB.enumDBType.SQL_Server
            '        '        Dim lst As Generic.List(Of String) = .GetTableListAll
            '        '        If WarningMsgFmt("Do you want to permanently delete all {0} data and Support tables in the server database ({1}) associated with this project (the database itself must be removed by a database administrator)?", lst.Count, .DB.DataSource) = Windows.Forms.DialogResult.OK Then
            '        '            For Each tbl As String In lst
            '        '                .DB.DropTable(tbl)
            '        '            Next
            '        '        End If
            '        'End Select
            '    Case Windows.Forms.DialogResult.Cancel
            '        Exit Sub
            'End Select
            'If ThisProject IsNot Nothing Then .Dispose()

            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub RemoveProject(ByVal ProjectName As String)
        Try
            With IniFile
                If StringsEqual(ProjectName, "Settings") Then Exit Sub
                If Not .DeleteProject(ProjectName) Then Exit Sub
                If Project IsNot Nothing AndAlso ProjectName = Project.Name Then
                    If .GetProjectNames.Count = 0 Then
                        .SetKey(clsWRDBIniFile.enumSection.Application, clsWRDBIniFile.enumKey.AppLastProjectName, "")
                    Else
                        .SetKey(clsWRDBIniFile.enumSection.Application, clsWRDBIniFile.enumKey.AppLastProjectName, .GetProjectNames(0))
                    End If
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfig.Click
        Try
            'don't need to be supervisor the change (otherwise could be stuck forever!)
            'If Not SupervisorEnabled() Then Exit Sub
            With New FolderBrowserDialog
                .ShowNewFolderButton = True
                AppDataPath = GetSetting(REGAPP, "General", "AppDataPath", AppDataPath)
                .SelectedPath = AppDataPath
                .Description = "Specify location of WRDB configuration file which contains all WRDB project information:"
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    If My.Computer.FileSystem.FileExists(.SelectedPath & "\WRDB.ini") OrElse WarningMsg("A WRDB configuration file (WRDB.ini) was not found in that directory. Do you want to create an empty configuration file in this directory?") = Windows.Forms.DialogResult.OK Then
                        'close all browsers
                        For Each f As Form In WRDBForms
                            f.Close()
                        Next
                        AppDataPath = .SelectedPath
                        SaveSetting(REGAPP, "General", "AppDataPath", AppDataPath)
                        Dim IniFile As New clsWRDBIniFile
                        If Not IniFile.Exists Then IniFile.Create()
                        MainWRDB = New WRDB.Lib.clsWRDB
                    End If
                End If
                .Dispose()
            End With
            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub
End Class
